import { useEffect } from 'react';

const useIframeMessage = (listeners) => {
  useEffect(() => {
    const onMessage = (event) => {
      listeners.forEach(listener => {
        try {
          if (listener){
            listener(event.data);
          }
        } catch(e) {
          window.console.error(e);
        }
      });
    };

    window.addEventListener('message', onMessage, false);

    return () => window.removeEventListener('message', onMessage);
  });
};

export default useIframeMessage;
